# encoding: utf-8
import re, requests

from app.extensions import log, db
from flask_restplus import Resource
from app.extensions.api import Namespace
from app.modules.common.utils import DbCommit, checkToken
from app.modules.common.schemas import BaseSchema
from . import parameters, schemas, zentao
from app.modules.projectPlan.models import PlanMember
from app.modules.projectPlan.common import getPlanByParam
from config import BaseConfig

ZenTao = zentao.ZenTao()

api = Namespace('zentao', description = "查询禅道信息")  # pylint: disable=invalid-name


@api.route('/getProjectPlanInfoByUrl')
class GetProjectPlanInfoByUrl(Resource):
    @api.parameters(parameters.GetProjectPlanInfoByUrlParameters())
    @api.response(schemas.ProjectPlanInfoSchema(many = False))
    @checkToken
    def get(self, args, **kwargs):
        """
        根据禅道url查询项目信息
        :param args:
        :return:
        """
        log.info("============== start query project plan info by zentao url ==============")
        _zentao_url = args['zentao_url']
        return getProjectPlanInfoByUrl(_zentao_url)


def getProjectPlanInfoByUrl(_zentao_url):
    log.info("============== zentao_url is %s ==============" % _zentao_url)
    _projectId = re.sub("(http://)(\\S*)(projectID=|project=)([0-9]+)(&|$)(\\S*)", "\\4", _zentao_url)
    if re.search("(http://)(\\S*)(projectID=|project=)([0-9]+)(&|$)(\\S*)", _zentao_url) is None:
        _msg = '根据禅道项目url查询项目信息，url格式错误'
        log.error("============== %s ==============" % _msg)
        return {'success': False, 'msg': _msg}

    if _projectId is None or _projectId == '':
        _msg = '根据禅道项目url查询项目信息，url参数projectID错误'
        log.error("============== %s ==============" % _msg)
        return {'success': False, 'msg': _msg}

    _projectView = ZenTao.ProjectView(_projectId)
    if _projectView is None:
        _msg = '根据禅道项目url查询项目信息为空'
        log.error("============== %s ==============" % _msg)
        return {'success': False, 'msg': _msg}
    _projectTeam = ZenTao.ProjectTeam(_projectId)
    _projectView['members'] = _projectTeam
    _projectView['PM_name'] = None
    for _user in _projectTeam:
        if _user['account'] == _projectView['PM']:
            _projectView['PM_name'] = _user['realname']
            break
    if _projectView['PM_name'] is None:
        _projectView['PM_name'] = _projectView['PM']

    _projectView['isIdExist'] = False

    if getPlanByParam(zt_id = _projectId, withCache = True) is not None:
        _projectView['isIdExist'] = True
    return {'success': True, 'msg': '', 'data': _projectView}


@api.route('/initProjectPlanInfoByProjectId')
class InitProjectPlanInfoByProjectId(Resource):
    @api.parameters(parameters.InitProjectPlanByProjectIdParameters())
    @api.response(BaseSchema(many = False))
    @checkToken
    def get(self, args, **kwargs):
        """
        根据禅道id更新项目信息
        :param args:
        :return:
        """
        log.info("============== start init project plan info by zentao id ==============")
        _zentao_id = args['zentao_id']
        log.info("============== zentao_id is %s ==============" % _zentao_id)

        return initProjectPlanInfoByProjectId(_zentao_id = _zentao_id)


def initProjectPlanInfoByProjectId(_zentao_id = None):
    log.info('app.modules.zentao.resources.initProjectPlanInfoByProjectId zentao id is %s' % _zentao_id)
    if _zentao_id is None:
        _msg = "zentao id is none"
        log.error("============== %s ==============" % _msg)
        return {'success': False, 'msg': _msg}
    _info = getPlanByParam(zt_id = _zentao_id)
    if _info is None:
        _msg = "项目 %s 不存在" % _zentao_id
        log.error("============== %s ==============" % _msg)
        return {'success': False, 'msg': _msg}

    _projectView = ZenTao.ProjectView(_zentao_id)
    if _projectView is None:
        _msg = '根据禅道项目url查询项目信息为空'
        log.error("============== %s ==============" % _msg)
        return {'success': False, 'msg': _msg}
    _projectTeam = ZenTao.ProjectTeam(_zentao_id)
    _projectView['members'] = _projectTeam
    _projectView['PM_name'] = None
    for _user in _projectTeam:
        if _user['account'] == _projectView['PM']:
            _projectView['PM_name'] = _user['realname']
            break
    if _projectView['PM_name'] is None:
        _projectView['PM_name'] = _projectView['PM']

    _info.plan_name = str(_projectView['name']).replace(' ', '')
    _info.start_date = _projectView['begin']
    _info.end_date = _projectView['end']
    _info.PM = _projectView['PM']
    _info.PM_name = _projectView['PM_name']
    _info.link_product = ZenTao.ProjectProduct(_zentao_id)

    _rtn = DbCommit(cleanPlan = True)
    if not _rtn['success']:
        return _rtn
    # 调用ucloud-master修改虚拟机申请的结束时间
    _url = BaseConfig.UCLOUD_MASTER_URL + '/apply_record/updateApplyEndTime?plan_id=' + _info.plan_id + '&to_date=' + str(
        _info.end_date)
    _rtn = requests.get(url = _url).content
    log.info('app.modules.zentao.resources.initProjectPlanInfoByProjectId update ucloud master . url=%s . rtn=%s' % (
        _url, _rtn))
    return DbCommit(cleanPlan = True)


@api.route('/initProjectPlanMembersByProjectId')
class InitProjectPlanMembersByProjectId(Resource):
    @api.parameters(parameters.InitProjectPlanByProjectIdParameters())
    @api.response(BaseSchema(many = False))
    @checkToken
    def get(self, args, **kwargs):
        """
        根据禅道id更新项目人员信息
        :param args:
        :return:
        """
        log.info("============== start init project plan members by zentao id ==============")
        _zentao_id = args['zentao_id']
        return initProjectPlanMembersByProjectId(_zentao_id)


def initProjectPlanMembersByProjectId(_zentao_id):
    log.info("============== zentao_id is %s ==============" % _zentao_id)
    _info = getPlanByParam(zt_id = _zentao_id)
    if _info is None:
        _msg = "项目 %s 不存在" % _zentao_id
        log.error("============== %s ==============" % _msg)
        return {'success': False, 'msg': _msg}

    _projectView = ZenTao.ProjectView(_zentao_id)
    if _projectView is None:
        _msg = '根据禅道项目url查询项目信息为空'
        log.error("============== %s ==============" % _msg)
        return {'success': False, 'msg': _msg}

    _projectTeam = ZenTao.ProjectTeam(_zentao_id)
    if _projectTeam is None:
        _msg = '根据禅道项目url查询项目人员为空'
        log.error("============== %s ==============" % _msg)
        return {'success': False, 'msg': _msg}

    _projectView['PM_name'] = None
    for _user in _projectTeam:
        if _user['account'] == _projectView['PM']:
            _projectView['PM_name'] = _user['realname']
            break
    if _projectView['PM_name'] is None:
        _projectView['PM_name'] = _projectView['PM']

    _info.PM = _projectView['PM']
    _info.PM_name = _projectView['PM_name']

    db.session.execute(
        "DELETE from plan_member where plan_id = :_plan_id", {'_plan_id': _info.plan_id})

    for _user in _projectTeam:
        _u = PlanMember(plan_id = _info.plan_id, account = _user['account'], realname = _user['realname'])
        db.session.add(_u)

    return DbCommit(cleanPlan = True)


def createPlanBuild(_plan_info, _today, **kwargs):
    if _plan_info.link_product is None or len(str(_plan_info.link_product).strip()) == 0:
        return False

    if kwargs['login_user_zt_account'] is None:
        return False

    _product = str(_plan_info.link_product).split(',')[0]
    _files = {'product': (None, _product), 'name': (None, '%s_%s' % (_plan_info.plan_name, _today)),
              'builder': (None, kwargs['login_user_zt_account']), 'date': (None, '%s' % _today)}
    _buildId = ZenTao.AddBuild(_plan_info.zt_id, _files)
    if _buildId is not None:
        _json = {'product': _product, 'project': _plan_info.zt_id, 'build': _buildId, 'status': 'wait',
                 'owner': kwargs['login_user_zt_account'], 'pri': '0', 'begin': '%s' % _today, 'end': '%s' % _today,
                 'name': '%s_%s' % (_plan_info.plan_name, _today)}
        ZenTao.AddTestTask(_plan_info.zt_id, _buildId, _json)
    return True


def saveZentaoPlanMembers(projectId, accounts):
    """
    保存禅道项目成员列表
    :param projectId: 禅道项目id
    :param accounts: 成员account列表  list
    :return:
    """
    if not accounts:
        return

    _projectTeam = ZenTao.ProjectTeam(projectId)
    if _projectTeam:
        for _user in _projectTeam:
            if _user['account'] in accounts:
                accounts.remove(_user['account'])
            else:
                ZenTao.DeletePlanMembers(projectId, _user['account'])
    _data = {}
    for account in accounts:
        _data['accounts[%s]' % (accounts.index(account) + 1)] = account
        # _data['roles[]']='开发'
        # _data['days[]']='1'
        # _data['hours[]']='2'
        _data['modes[%s]' % (accounts.index(account) + 1)] = 'create'
    ZenTao.UpdatePlanMembers(projectId, _data)
